package com.hinner.config.security;

import cn.hutool.core.util.ObjectUtil;
import com.hinner.common.exception.UserCountLockException;
import com.hinner.entity.SysUser;
import com.hinner.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 这个类可以被看作是利用spring security进行查表登录，和我们的用户登录表还是有点区别的
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    // 整合用户登录表的接口
    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据用户名加载用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getUserByUserName(username);
        // 首先用户要存在，其次用户状态用正常
        if (ObjectUtil.isNull(user)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }else if ("1".equals(user.getStatus())){
            throw new UserCountLockException("该账号已被封禁，请联系管理员！"); //自定义异常
        }
        return new User(user.getUsername(),user.getPassword(),getAuthorities(user.getId()));
    }

    /**
     * 用户详情：获取用户角色和权限
     * @param userId
     * 要求的格式：Role_admin,system:user:list,...... 这种字符串
     * @return
     */
    public List<GrantedAuthority> getAuthorities(Long userId) {
        // 获取该用户的权限信息：角色信息、角色菜单信息
        String authority = sysUserService.getUserAuthorityInfo(userId);
//        System.out.println("authority = " + authority);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
